package com.h117121.fashionshop.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.h117121.fashionshop.controller.generic.GenericController;
import com.h117121.fashionshop.core.dom.Account;
import com.h117121.fashionshop.core.dom.Cart;
import com.h117121.fashionshop.core.exception.EntityNotFoundException;

@Controller
@RequestMapping("/product")
public class ProductDetailController extends GenericController {

	@RequestMapping(method = RequestMethod.GET)
	protected String showPage(HttpServletRequest request) {
		if (request.getParameter("id") != null) {
			long id = Long.parseLong(request.getParameter("id"));

			try {
				businessService.raiseView(businessService.getProduct(id));
				request.setAttribute("product", businessService.getProduct(id));
				String fullUrl = request.getRequestURL().toString() + "?"
						+ request.getQueryString();
				request.setAttribute("fullUrl", fullUrl);
			} catch (EntityNotFoundException e) {
				request.setAttribute("notfound", true);
				return "ProductDetailPage";
			}
		} else {
			return "redirect:/home";
		}

		return "ProductDetailPage";
	}

	@RequestMapping(method = RequestMethod.POST)
	protected String addItem(@RequestParam long productId,
			@RequestParam int quantity, HttpServletRequest request) {
		Account account = (Account) request.getSession()
				.getAttribute("account");
		if (account == null) {
			return "redirect:/login";
		}

		Cart cart = account.getCart();
		try {
			cart.add(businessService.getProduct(productId), quantity);
		} catch (EntityNotFoundException e) {
			request.setAttribute("notfound", true);
			return "ProductDetailPage";
		}
		return "redirect:/product?id=" + productId;
	}
}
